<template>
	<gui-page>
		<template v-slot:gBody>
			<view class="login" style="padding:50rpx;">
				<view class="login-langType" style="width:200rpx;">
					<gui-segmented-control :items="cates" :current="langIndex" borderRadius="40rpx"
						customStyle="border-radius:40rpx;height:40rpx;" @change="switchLanguage">
					</gui-segmented-control>
				</view>
				<view style="height:150rpx;"></view>
				<view class="gui-flex gui-row gui-justify-content-center">
					<gui-image v-show="false" src="../../static/logo.jpg" borderRadius="10rpx"></gui-image>
				</view>
				<view style="margin-top:80rpx;">
					<form @submit="submit">
						<view>
							<text class="gui-text-small" style="color: #fff;">{{ $t('login.username') }}</text>
						</view>
						<view class="gui-border-b">
							<input type="text" class="gui-form-input" name="username" placeholder-style="color:#fff"
								style="color: #fff;" :value="data.username" :placeholder="$t('login.inputUserName')" />
						</view>
						<view class="gui-margin-top">
							<text class="gui-text-small" style="color: #fff;">{{ $t('login.password') }}</text>
						</view>
						<view class="gui-border-b">
							<input type="password" class="gui-form-input" name="password" placeholder-style="color:#fff"
								style="color: #fff;" :placeholder="$t('login.inputPassword')" v-model="data.password" />
						</view>
						<view class="gui-margin-top checkbox">
							<checkbox-group @change="checkboxChange()">
								<checkbox class="checkbox-check" :checked="data.checked === true"
									placeholder-style="color:#fff" style="color: #fff;" />
							</checkbox-group>

							<text class="gui-text-small checkbox-spec"
								style="color: #fff;">{{ $t('login.rememb') }}</text>
						</view>
						<view style="margin-top:38rpx;">
							<button type="default" class="gui-button gui-bg-primary gui-noborder" formType="submit"
								style="border-radius:50rpx;">
								<text class="gui-color-white gui-button-text">{{ $t('login.login') }}</text>
							</button>
						</view>
						<view style="margin-top:38rpx;">
							<button type="primary" plain="true" class="gui-button borderbut"
								style="border-radius:50rpx;" @click="handelServeSeting">
								<text
									class="gui-color-white gui-button-text color">{{ $t("navigationBar.configurationServices") }}</text>
							</button>
						</view>
					</form>
				</view>
			</view>
			<uni-popup ref="inputDialog" type="dialog">
				<view class="input-dialog-box">
					<view class="inputDialog-title">
						<view class="line"></view>
						<view class="title">{{ $t("navigationBar.serviceSetting") }}</view>
						<view class="line"></view>
					</view>
					<form class="form" @submit="formSubmit">
						<view class="uni-form-item">
							<view class="title">{{ $t("navigationBar.address") }}：</view>
							<uni-easyinput class="uni-mt-5" suffixIcon="list" v-model="data.adress"
								placeholder="示例http://10.1.5.10:9770" @iconClick="iconClick"></uni-easyinput>
							<!-- <view class="inputBox">
								<uni-easyinput class="uni-mt-5" suffixIcon="search" v-model="value" placeholder="右侧图标" @iconClick="iconClick"></uni-easyinput>
								<input class="uni-input" placeholder="示例http://10.1.5.10:9770" v-model="data.adress"  name="oldPassword"/>
							</view> -->
						</view>
						<view class="inputDialog-bottom">
							<button class="button" type="default"
								@click="handelCloseServeSeting">{{ $t("popup.cancel") }}</button>
							<button class="button sure" type="primary"
								form-type="submit">{{ $t("popup.confirm") }}</button>
						</view>
					</form>
				</view>
			</uni-popup>

			<!--最底部弹出的选择服务的列表-->
			<uni-popup ref="baseServiceListDialog" type="bottom">
				<view class="ServiceContainer">
					<view class="ServiceItem" v-for="(item, index) in servcieitemList.itemList" :key="index"
						@click="setBaseServcie(index)">
						<text>{{ item }}</text>
						<view @click.stop="removeBaseServieItem(item)">
							<uni-icons type="closeempty" size="26"></uni-icons>
						</view>

					</view>
					<view class="baseServiceListDialogCancel" @click="cancelServiceDialog()">{{ $t("popup.cancel") }}
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>


<script setup>
import {
	getLang
} from '@/locale/index';
import {
	reLaunch
} from '@/utils/routerSkip.js'
import graceChecker from "@/Grace6/js/checker.js";
import {
	regExpDomainName
} from '@/utils/index.js'
import {
	logIn,
	getUserPermission,
	getCurrentUser,
	getDetailByCodeId
} from '@/api/api.js';
import {
	TOKEN,
	FINE_GRIT,
	PREMISSIONS_PAGE,
	HISTORY_SET_BASEURL,
	SET_BASEURL,
	USERINFO,
	USERNAME,
	PASSWORD,
	PRINT_BASE
} from '@/constant/index.js'
import { TEST_URL, PROD_URL, PRINT_BASE_URL } from '@/constant/config.js'
import {
	reactive,
	ref,
	onMounted,
	computed,
	watch
} from "vue";
import {
	useI18n
} from 'vue-i18n';
import {
	useStore
} from "vuex";
let store = useStore();
const {
	t
} = useI18n();
let isAndroid = ref(false);
let langIndex = ref();
let inputDialog = ref(null)
let baseServiceListDialog = ref(null)
let data = reactive({
	username: uni.getStorageSync(USERNAME) || '',
	password: uni.getStorageSync(PASSWORD) || '',
	serveSetingBool: false,
	adress: uni.getStorageSync(SET_BASEURL) || "http://10.1.5.10:9770",
	checked: uni.getStorageSync(PASSWORD) != '' || false
})
let langTypes = ["zh-Hans", "en", "es"]
let cates = computed(() => {
	return [t('login.simplified'), t('login.english'), t('login.spanish')]
})
let servcieitemList = reactive({ itemList: [] });
data.serveSetingBool = computed(() => {
	return store.state.serveSetingBool
})
//把扫描条码变为物料集合的二维数组
watch(() => data.serveSetingBool, (newVal) => {
	if (newVal) {
		setTimeout(() => {
			inputDialog.value.open();
		}, 1000)
	}
}, {
	immediate: true,
	deep: true
});
onMounted(() => {
	let systemInfo = uni.getSystemInfoSync();
	//判断当前用户机型是否为安卓坏境
	isAndroid.value = systemInfo.platform.toLowerCase() === 'android';
	let langType = uni.getLocale()
	langIndex.value = langTypes.findIndex(x => x == langType)
})
const formSubmit = (e) => {
	if (!regExpDomainName(data.adress)) {
		uni.showToast({
			title: t('pageTranslation.addressCantMeet'),
			icon: "none"
		});
		return
	}
	uni.setStorageSync(SET_BASEURL, data.adress)
	let historySetBaseList = uni.getStorageSync(HISTORY_SET_BASEURL) || []
	// 判断与历史数据是否重复
	let isRepetition = historySetBaseList.some((item) => {
		return item == data.adress
	})
	if (!isRepetition) {
		historySetBaseList.unshift(data.adress);
		historySetBaseList = historySetBaseList.length >= 3 ? historySetBaseList.slice(0, 3) : historySetBaseList
		uni.setStorageSync(HISTORY_SET_BASEURL, historySetBaseList)
	}
	inputDialog.value.close();
	try {
		plus.runtime.restart()
	} catch (error) {

	}
}
const handelCloseServeSeting = () => {
	store.commit('updateServeSetingBool', 0)
	inputDialog.value.close();
}
const handelServeSeting = () => {
	inputDialog.value.open();
}
const iconClick = () => {
	servcieitemList.itemList = uni.getStorageSync(HISTORY_SET_BASEURL) || []
	if (!servcieitemList.itemList.length) {
		uni.showToast({
			title: t('JsInternational.noRelatedRecord'),
			icon: "none"
		});
		return
	}
	// uni.showActionSheet({
	// 	itemList: itemList,
	// 	success: function (res) {
	// 		data.adress = itemList[res.tapIndex]
	// 	},
	// 	fail: function (res) {
	// 	}
	// });
	//弹出选择服务的窗口
	baseServiceListDialog.value.open();
}

//选择某个服务
function setBaseServcie(index) {
	data.adress = servcieitemList.itemList[index]
	baseServiceListDialog.value.close()
}
//移除某个服务
function removeBaseServieItem(item) {
	servcieitemList.itemList = servcieitemList.itemList.filter(e => e != item)
	uni.setStorageSync(HISTORY_SET_BASEURL, servcieitemList.itemList)
	baseServiceListDialog.value.close()
}

//取消
function cancelServiceDialog() {
	baseServiceListDialog.value.close()
}

// 登录操作
function submit(e) {
	if (data.checked) {
		uni.setStorageSync(PASSWORD, data.password)
	} else {
		uni.removeStorage({ //选中之后取消删除存储的密码
			key: PASSWORD,
			success() {
				console.log('删除成功')
			}
		})
	}
	// 表单数据
	var formData = e.detail.value;
	console.log(formData);
	// 利用 graceUI 的表单验证工具进行验证
	//定义表单规则
	var rule = [
		// {
		// 	name: "username",
		// 	checkType: "string",
		// 	checkRule: "5,50",
		// 	errorMsg: t('login.account-remind')
		// },
		// {
		// 	name: "password",
		// 	checkType: "string",
		// 	checkRule: "6,100",
		// 	errorMsg: t('login.password-remind')
		// },
	];
	var checkRes = graceChecker.check(formData, rule);
	if (checkRes) {
		logIn({
			password: formData.password,
			userNameId: formData.username
		}).then(res => {
			let data = res
			if (data.statusCode == 200) {
				uni.setStorageSync(USERNAME, formData.username)
				// uni.setStorageSync(PASSWORD, formData.password)
				let token = data.token;
				token = token.split('bearer;')[1];
				uni.setStorageSync(TOKEN, token);
				getUserInfo()
				getUserPermissionFn()
			} else {
				uni.showToast({
					title: data.message,
					icon: "none"
				});
			}
		})
			.catch((err) => {
				uni.showToast({
					title: t('JsInternational.requestFailed'),
					icon: "none"
				});
			})
	} else {
		uni.showToast({
			title: graceChecker.error,
			icon: "none"
		});
	}
	let serverIp
	getDetailByCodeId().then(res => {
		console.log('服务器ip地址' + res.value)
		serverIp = res.value
		uni.setStorageSync(PRINT_BASE, serverIp)
		let printId = uni.getStorageSync(PRINT_BASE)
		let printUrl = printId.length > 0 ? printId : PRINT_BASE_URL

	})
}
async function getUserInfo() {
	let res = await getCurrentUser({})
	if (res) {
		uni.setStorageSync(USERINFO, res);
	} else {
		uni.showToast({
			title: t('JsInternational.userInformationFailed'),
			icon: "none"
		});
	}
}
// 获取用户权限
function getUserPermissionFn() {
	getUserPermission().then(res => {
		if (res.menu.length) {
			uni.showToast({
				title: t('login.login-success'),
				icon: "none"
			});
			uni.setStorageSync(FINE_GRIT, res.button);
			uni.setStorageSync(PREMISSIONS_PAGE, res.menu);
			setTimeout(() => {
				reLaunch({
					url: '/pages/index/index'
				});
			}, 1000)
		}
	})
}

// 语言切换
function switchLanguage(index) {
	console.log(index)
	let type = langTypes[index];
	// #ifdef APP-PLUS
	if (isAndroid) {
		uni.showModal({
			content: t('login.language-change-confirm'),
			success: (res) => {
				if (res.confirm) {
					langIndex.value = index
					getLang(type)
				}
			}
		})
	} else {
		langIndex.value = index
		getLang(type)
	}
	// #endif
	// #ifndef APP-PLUS
	getLang(type)
	langIndex.value = index
	// #endif
}
// 点击记住密码存储到本地
const checkboxChange = () => {
	data.checked = !data.checked
	console.log(data.checked)
}
</script>

<style lang="scss" scoped>
.login-logo {
	width: 180rpx;
	height: 180rpx;
	font-size: 80rpx;
	text-align: center;
	line-height: 120rpx;
	padding: 30rpx;
	border-radius: 18rpx;
}

.other-login-icons {
	width: 88rpx;
	height: 88rpx;
	text-align: center;
	font-size: 70rpx;
	margin: 20rpx;
}

.login {
	position: relative;
	background: url('@/static/login-bj.jpg') no-repeat;
	background-size: 100% 100%;
	height: calc(100vh - 100rpx);

	::v-deep .gui-segmented-control-item {
		height: 40rpx;
		line-height: 40rpx;
	}

	.login-langType {
		position: absolute;
		top: 40rpx;
		right: 20rpx;
	}
}

.inputDialog-title {
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 30rpx;
	height: 100rpx;
	color: #333;

	.title {
		margin: 0rpx 24rpx;
	}

	.line {
		width: 25%;
		background: #333;
		height: 1rpx;
	}
}

.form {
	background: #fff;

	.uni-form-item {
		display: flex;
		align-items: center;
		box-sizing: border-box;
		padding: 24rpx;
		background: #fff;
		overflow: hidden;
		font-size: 30rpx;

		.title {
			color: #333;
			width: 120rpx;
		}

		.inputBox {
			flex: 1;
			border: 1rpx solid #A5A5A5;
			border-radius: 10rpx;
			height: 70rpx;
			padding: 0rpx 10rpx;
			box-sizing: border-box;
		}

		.uni-input {
			width: 100%;
			color: #333;
			height: 100%;
			font-size: 30rpx;
		}
	}

	// .checkbox {
	// 	margin-top: 30rpx;
	// 	display: flex;
	// 	color: #fff;
	// 	align-items: center;
	// 	justify-content: flex-end;
	// }
}

.borderbut {
	background: #fff !important;
	// border: 2rpx solid #008AFF !important;
}

.color {
	color: #008AFF !important;
}

.inputDialog-bottom {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx;
	box-sizing: border-box;

	.button {
		margin: 0rpx !important;
		color: #666;
		width: 48%;
	}

	.sure {
		background-color: #008AFF !important;
		color: #fff;
	}

}

.checkbox {
	display: flex;
	flex-direction: row;
	line-height: 100%;

	&-check {
		width: 10%;
		text-align: right;
		box-sizing: border-box;
		// margin-left: 10rpx;
	}

	&-spec {
		flex: 1;
		font-size: 28rpx;
		padding-left: 10rpx;
		line-height: 160%;
	}
}

.ServiceContainer {
	padding: 15rpx;
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	justify-content: center;
}

.ServiceItem {
	background-color: #fff;
	height: 80rpx;
	line-height: 80rpx;
	display: inline-flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	width: 99%;
	padding-left: 10rpx;
	border-bottom: 2rpx solid #ededed;
}

.baseServiceListDialogCancel {
	text-align: center;
	background-color: #fff;
	height: 80rpx;
	line-height: 80rpx;
	width: 100%;
	border-radius: 10rpx;
	margin-top: 20rpx;
}
</style>
